const app = getApp()
const db = wx.cloud.database()
const _ = db.command
Page({
  data: {
    avatarUrl: './user-unlogin.png',
    userInfo: null,
    logged: false,
    takeSession: false,
    requestResult: '',
    // chatRoomEnvId: 'release-f8415a',
    chatRoomCollection: 'privateChat',
    chatRoomGroupId: 'demo',
    chatRoomGroupName: '公屏',
    // functions for used in chatroom components
    onGetUserInfo: null,
    getOpenID: null,
    anonymous: false
  },

  onLoad: function (event) {
    // 获取用户信息
    wx.getSetting({
      success: res => {
        if (res.authSetting['scope.userInfo']) {
          // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
          wx.getUserInfo({
            success: res => {
              this.setData({
                avatarUrl: res.userInfo.avatarUrl,
                userInfo: res.userInfo
              })
            }
          })
        }
      }
    })

    this.setData({
      onGetUserInfo: this.onGetUserInfo,
      getOpenID: this.getOpenID,
    })

    wx.getSystemInfo({
      success: res => {
        //console.log('system info', res)
        if (res.safeArea) {
          const {
            top,
            bottom
          } = res.safeArea
          this.setData({
            containerStyle: `padding-top: ${(/ios/i.test(res.system) ? 10 : 20) + top}px; padding-bottom: ${20 + res.windowHeight - bottom}px`,
          })
        }
      },
    })

    //获取聊天groupId
    //实名树洞
    db.collection('privateChatId').where({
      id: _.or(_.eq(app.globalData.openid + event.id), _.eq(event.id + app.globalData.openid))
    }).get().then(res => {
      //console.log(res)
      if (res.data.length == 0) {
        var time = new Date().getTime()
        db.collection('privateChatId').add({
          data: {
            id: app.globalData.openid + event.id,
            name: app.globalData.name + event.name,
            createTime: time,
            newMsg: 0
          }
        }).then(res => {
          console.log(res)
          this.setData({
            chatRoomGroupId: app.globalData.openid + event.id,
            chatRoomGroupName: event.name
          })
        })
      } else {
        console.log('old chat: ' + res.data[0].id)
        this.setData({
          chatRoomGroupId: res.data[0].id,
          chatRoomGroupName: event.name
        })
        wx.cloud.callFunction({
          name: 'updateChat',
          data: {
            id: res.data[0].id,
            openid:app.globalData.openid,
            newMsg: false
          },
        })
      }
    })

  },

  getOpenID: async function () {
    if (this.openid) {
      return this.openid
    }
    const {
      result
    } = await wx.cloud.callFunction({
      name: 'login',
    })
    return result.openid
  },

  onGetUserInfo: function (e) {
    if (!this.logged && e.detail.userInfo) {
      this.setData({
        logged: true,
        avatarUrl: e.detail.userInfo.avatarUrl,
        userInfo: e.detail.userInfo
      })
    }
  },
})